import { defineStore } from "pinia";
import {  totalProductDeleteDel, totalProductDetailGet } from "@/api/allProduct"
import type { FormInstance, FormRules } from 'element-plus'
import mittBus from '@/utils/mitt';

import { systemMessagePagePost, smsSendPost } from "@/api/serviceSystem"
import { useEnumStore } from "@/store/enumeration"
import { ElMessage } from "element-plus";
import useInstance from '@/hooks/useInstance';
export const serviceSystemListStore = defineStore("serviceSystemListStoreId", () => {
    const { sendStatus } = useEnumStore()
    const { global } = useInstance();

    const detailData = ref([
        {
            type: "text",
            prop: "supplierType",
            name: "供应商类型",
            value: null
        },

    ])
    const tableProp = reactive(
        {
            name: "serviceSystem",
            propsList: [

                {
                    prop: 'recipient',
                    label: '接收人',
                    type: 'normal',
                    minWidth: '100px',
                    hidden: true,
                },
                {
                    prop: 'sendTime',
                    label: '发送时间',
                    type: 'normal',
                    minWidth: '170px',
                    hidden: true,
                },
                {
                    prop: 'status',
                    label: '发送状态',
                    type: 'normal',
                    minWidth: '70px',
                    hidden: true,
                },
                {
                    prop: 'content',
                    label: '短信内容',
                    type: 'normal',
                    minWidth: '400px',
                    hidden: true,
                },
                {
                    prop: 'respMsg',
                    label: '响应记录',
                    type: 'normal',
                    minWidth: '200px',
                    hidden: true,
                },
                {
                    prop: 'templateCode',
                    label: '模版编码',
                    type: 'normal',
                    minWidth: '100px',
                    hidden: true,
                },
                {
                    prop: 'messageId',
                    label: '消息ID',
                    type: 'normal',
                    minWidth: '100px',
                    hidden: true,
                },

                // {
                //     type: 'handle',
                //     label: '操作',
                //     minWidth: '200',
                //     btnType: ' link',
                //     slotName: 'handle',
                //     hidden: true,
                // }
            ]
        })
    const operateTime = ref([])
    const sendMessage = reactive({
        mobile: null,//手机
        templateCode: null,//模板code
        templateParams: {
            additionalProp1: null,
            additionalProp2: null,
            additionalProp3: null,
        },//
    })
    const rules = reactive<FormRules>({
        mobile: [
            {
                required: true,
                trigger: 'blur',
                message: "请输入用户手机号"
            },
            {
                trigger: 'blur',
                message: "请输入正确的手机号",
                pattern: /^1[3-9]\d{9}$/
            }
        ],
        templateCode: [
            {
                required: true,
                trigger: 'blur',
                message: "请选择模版类型"
            }
        ]
    })
    const messageRef = ref<FormInstance>()

    const listSearch = reactive({
        orders: ["created_time desc"],
        condition: {
            recipient: null,//接收人 
            sendTime: null,//发送时间 
            status: null,//发送状态 
            content: null,//短信内容 
            templateCode: null,//模版编码 
            respMsg: null,//响应记录 
            startTime: null,//响应记录 
            endTime: null,//响应记录 
        },
        pageSize: 20,
        pageNum: 1
    });
    const pageParams = reactive({
        tableHeight: 400,
        total: 0,
        loadIng: false,
        tableData: [],
        clientWidth:0
    })
    const addEditRef = ref<{ show: (title: string, row?: any) => void }>()
    const detailRef = ref<{ show: (title: string, row?: any) => void }>()

    const getData1 = async (type: string) => {

        pageParams.loadIng = true
        if (type == 'reset') {
            operateTime.value = []
            listSearch.pageNum = 1
            listSearch.pageSize = 20
            Object.keys(listSearch.condition).forEach((it: any) => {
                listSearch.condition[it] = null
            })
        }
        try {
            const res = await systemMessagePagePost(listSearch)
            if (res.code == 20000) {
                pageParams.tableData = res.data.records.map((item: any) => {

                    return {
                        ...item,
                        status: sendStatus[item.status - 1]?.value
                    }
                })
                pageParams.total = res.data.total
                pageParams.loadIng = false
            }
        } catch (error) {
            pageParams.loadIng = false
            pageParams.tableData = []
            pageParams.total = 0
        }finally{
            mittBus.emit('scrollUpdate')
        }

    }
    const handPage = (page: any) => {
        listSearch.pageNum = page.pageNum
        listSearch.pageSize = page.pageSize
        getData1('search')
    }
    const timeChange = (time: any) => {
        console.log(time);
        if (time) {
            listSearch.condition.startTime = time[0]
            listSearch.condition.endTime = time[1]
        } else {
            listSearch.condition.startTime = null
            listSearch.condition.endTime = null
        }
        getData1('search')
    }
    const AddEditBtn = async (type: string, row?: any) => {
        if (type == 'add') {
            addEditRef.value?.show('add')
        } else {
            const res = await totalProductDetailGet({ id: row.id })

            addEditRef.value?.show('edit', res.data)
        }
    }
    const detailBtn = async (row: any) => {

        const res = await totalProductDetailGet({ id: row.id })

        detailRef.value?.show('edit', res.data)
    }
    const delBtn = async (row: any) => {
        const flag = await global.$myconfirm(`是否确定删除该数据？`)
        if (flag) {
            const res = await totalProductDeleteDel({ id: row.id })
            console.log(res.data);
            if (res.code == 20000) {
                ElMessage({
                    type: "success",
                    message: "数据删除成功"
                })
                getData1('search')
            } else {
                ElMessage({
                    type: "error",
                    message: "数据删除失败"
                })
            }
        }
    }
    const sendMessBtn = async () => {
        await messageRef.value?.validate(async (isOk: boolean) => {
            console.log(isOk);
            
            if (isOk) {
                try {
                    const res = await smsSendPost(sendMessage)
                    if (res.code == 20000) {
                        ElMessage({
                            type: "success",
                            message: "短信发送成功"
                        })
                        getData1('reset')
                    }
                } catch (error) {
                    ElMessage({
                        type: "error",
                        message: "短信发送失败失败"
                    })
                }
            }
        })

    }

    return {
        detailData, tableProp, listSearch, pageParams, addEditRef, detailRef, operateTime, sendMessage, rules, messageRef,
        getData1, handPage, AddEditBtn, delBtn, detailBtn, timeChange, sendMessBtn
    }
})